//
//  MTOverlayView.m
//
//  Copyright 2010 The MITRE Corporation. All rights reserved.
//

#import "MTOverlayView.h"
#import "MTOverlay.h"
#import "MTOverlayTile.h"

@implementation MTOverlayView

- (id)initWithOverlay:(id <MKOverlay>)overlay
{
    if (self = [super initWithOverlay:overlay]) {
        
    }
    return self;
}

- (BOOL)canDrawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale
{
	NSLog(@"canDrawMapRect: origin %f/%f, size %f/%f, zoomScale %f", mapRect.origin.x, mapRect.origin.y, mapRect.size.width, mapRect.size.height, zoomScale);
    // Return YES only if there are some tiles in this mapRect and at this zoomScale.
    MTOverlay *overlay = (MTOverlay *)self.overlay;
    return [overlay.dataSource hasTilesInMapRect:mapRect zoomScale:zoomScale];  
}

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    MTOverlay *overlay = (MTOverlay *)self.overlay;
    
    // Get the list of tile images from the model object for this mapRect.  The
    // list may be 1 or more images (but not 0 because canDrawMapRect would have
    // returned NO in that case).
    NSArray *tilesInRect = [overlay.dataSource tilesInMapRect:mapRect zoomScale:zoomScale];
    
//    CGContextSetAlpha(context, tileAlpha);
	
    for (MTOverlayTile *tile in tilesInRect) {
        // For each image tile, draw it in its corresponding MKMapRect frame
        CGRect rect = [self rectForMapRect:tile.frame];
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGContextScaleCTM(context, 1/zoomScale, 1/zoomScale);
        CGContextTranslateCTM(context, 0, tile.image.size.height);
        CGContextScaleCTM(context, 1, -1);
        CGContextDrawImage(context, CGRectMake(0, 0, tile.image.size.width, tile.image.size.height), [tile.image CGImage]);
        CGContextRestoreGState(context);
//		[tile.image release];
    }
}
@end
